import React from 'react';
import get from 'lodash/get';
import PropTypes from 'prop-types';
import moment from 'moment-timezone';
import { FormattedMessage, injectIntl } from 'react-intl';
import { stripesConnect, IfPermission } from '@folio/stripes/core';
import {
  StripesConnectedSource
} from '@folio/stripes/smart-components';
import {
  Row,
  Col,
  ButtonGroup,
  Modal,
  Button,
  MultiColumnList,
  Checkbox,
  Field,
  Select
} from '@folio/stripes/components';
import SearchFrom from '../../components/party-rules/search-from'

class List extends React.Component {

    static manifest = Object.freeze({

        rulesQuery: { initialValue: '' },
        resultCount: { initialValue: 10 },
        rulesRecords: {
          type: 'okapi',
          path: 'party/rules',
          recordsRequired: '%{resultCount}',
          perRequest: 10,
          limitParam: 'limit',
          records: 'rulesGroup',
          GET: {
            params: {
              query: '( status = 1 ) sortBy year/sort.descending  metadata.updatedDate/sort.descending '
            }
          }
  
        } ,
        httpRulesSwitchInvoke: {
          type: 'okapi',
          accumulate: true,
          path: () => 'party/rules/switch'
        },
        httpRulesModifyInvoke: {
          type: 'okapi',
          accumulate: true,
          path: () => 'party/rules/modify'
        }
      });
  
      static propTypes = {
        stripes: PropTypes.shape({
          logger: PropTypes.object
        }).isRequired,
        resources: PropTypes.object,
        mutator: PropTypes.shape({
  
          rulesQuery: PropTypes.string,
          rulesRecords: PropTypes.shape({
            PUT: PropTypes.func.isRequired,
            POST: PropTypes.func.isRequired,
            GET: PropTypes.func.isRequired,
            DELETE: PropTypes.func.isRequired
          }),
          httpRulesSwitchInvoke: PropTypes.shape({
            PUT: PropTypes.func.isRequired,
          }) ,
          httpRulesModifyInvoke: PropTypes.shape({
       
            DELETE: PropTypes.func.isRequired
          }),
        }).isRequired,
        labelName: PropTypes.object,
        toModel:PropTypes.func,
        intl:PropTypes.object
      };
  

    constructor(props) {
        super(props);
        this.logger = props.stripes.logger;
        this.log = this.logger.log.bind(this.logger);
        this.state = {
          isOpen:false,
          switchObject:{},
          isDel:false
        };

    }
    
    componentDidMount() {
        this.source = new StripesConnectedSource(this.props, this.logger);
    }

    componentDidUpdate() {
        this.source.update(this.props, 'rulesRecords');
      }
  
      componentWillUnmount() {
        const { mutator, resources } = this.props;
  
        mutator.rulesQuery.replace('');
      }
  


    search=({ requestPreferences, creds, ...formData })=>{

    }
    moreData=()=>{
        if (this.source) {
            this.source.fetchMore(30);
          }
    }
    render() {
        const { resources, toModel ,intl} = this.props;
 
        if (this.source) {
            this.source.update(this.props, 'rulesRecords');
          }

        const columnMapping = {
            serialNumber:  <FormattedMessage id="ui-party.loans.columns.serialNumber" />,
            year:  <FormattedMessage id="ui-party.loans.columns.party.rules.year" />,
            late:  <FormattedMessage id="ui-party.loans.columns.party.rules.late" />,
            leave:  <FormattedMessage id="ui-party.loans.columns.party.rules.leave" />,
            absence:  <FormattedMessage id="ui-party.loans.columns.party.rules.absent" />,
            leaveEarly:  <FormattedMessage id="ui-party.loans.columns.party.rules.leave.early" />,
            prisonTermDay: <FormattedMessage id="ui-party.loans.columns.party.rules.prisonTermDay" />,
            openState:  <FormattedMessage id="ui-party.loans.columns.party.rules.openState" />,
            edit:  <FormattedMessage id="ui-party.loans.columns.operating" />,
    
        }
        const formatter = {
          serialNumber: item => [<span>{item.rowIndex + 1}</span>],
          openState: item =>{ 
            const openName = item.openState == "1" ? '已开启' : '未开启'
            return <div>{openName}</div>
          },
          edit: item=>{
           return  [
            <Button onClick={()=>{
              toModel('/rules/edit', { id:item.id });
           }}>
               <FormattedMessage id={"ui-party.loans.columns.operating.edit"}/>
            </Button>,
             <Button onClick={()=>{
                this.setState({isOpen:true,switchObject:item})
           }}>
             {item.openState =="1"?<span  >关闭</span>:<span  >开启</span>}
               {/* <FormattedMessage id={"ui-party.messageTemplate.data.state.enable"}/> */}
            </Button>,
           <Button style={{ border: '1px solid #900', color: ' #900' }} onClick={()=>{
            this.setState({isDel:true,switchObject:item})
          }}>
            <FormattedMessage id={"ui-party.systemLog.data.type.delete"}/>
        </Button>
           ]
          }
        }
        const totalCount = this.source ? this.source.totalCount() : 0;
        const dataList = get(resources, 'rulesRecords.records', []);

        const footer = (
          <React.Fragment>
          <Button buttonStyle="default"  onClick={()=>{
            this.setState({isOpen:false})
          }} ><FormattedMessage id={"ui-party.cancel"}/></Button> 
          <Button buttonStyle="primary" onClick={()=>{
              const {PUT}=this.props.mutator.httpRulesSwitchInvoke 
              let data =this.state.switchObject;
              const openState=data.openState == "1"?"0":"1";
              data.openState = openState
              delete data.rowIndex
              PUT(data).then(res=>{
                console.log(res)
                this.setState({isOpen:false,switchObject:{}})
              }).catch(e=>{
                console.debug(e)
              })
          }}><FormattedMessage id={"ui-party.saveAndExit"}/></Button>
          </React.Fragment>
       
        )
        const delFooter = (
          <React.Fragment>
          <Button buttonStyle="default"  onClick={()=>{
            this.setState({isDel:false,switchObject:{}})
          }} ><FormattedMessage id={"ui-party.cancel"}/></Button> 
          <Button buttonStyle="primary"  
           onClick={()=>{
              const {DELETE}=this.props.mutator.httpRulesModifyInvoke 
              let data =this.state.switchObject;
              DELETE({id:data.id})
              this.setState({isDel:false,switchObject:{}})
          }}><FormattedMessage id={"ui-party.systemLog.data.type.delete"}/></Button>
          </React.Fragment>
        )
        return (
          <div style={{ width:'610px', height:'700px' }}>
          <Modal 
          open={this.state.isOpen}  
          dismissible
          closeOnBackgroundClick
          onClose={()=>{
            this.setState({isOpen:false,switchObject:{}})
          }}
          label={<FormattedMessage id={"ui-party.prompt"}/>}
          footer={footer}
         >
           <div style={{textAlign:'center'}}>
              你确定{this.state.switchObject.openState ==1?<span style={{color:'red'}}>关闭</span>:<span style={{color:'red'}}>开启</span>}这个黑名单规则?
           </div>
        
         </Modal>

         <Modal 
          open={this.state.isDel}  
          dismissible
          closeOnBackgroundClick
          onClose={()=>{
            this.setState({isDel:false,switchObject:{}})
          }}
          label={<FormattedMessage id={"ui-party.prompt"}/>}
          footer={delFooter}
         >
           <div style={{textAlign:'center'}}>
              你确定 <span style={{color:'red'}}>删除</span> 这个黑名单规则?
           </div>
        
         </Modal>
          <SearchFrom onSubmit={this.search} openEdit={()=>{}} toModel={toModel}></SearchFrom>   
          <MultiColumnList
           interactive={false}
           height={700}
           width={'830px'}
           isEmptyMessage={<FormattedMessage id="ui-party.empty.list" />} // 空数据提示
            totalCount={totalCount}
            virtualize
            contentData={dataList}
            onNeedMoreData={this.moreData}
            columnMapping={columnMapping}
            pagingType="click"
            formatter={formatter}
            columnWidths={{
              serialNumber: '50px',
              year: '80px',
              late: '80px',
              leave: '80px',
              absence: '80px',
              leaveEarly: '80px',
              prisonTermDay: '80px',
              openState: '80px',
              edit: '200px'
            }}
            visibleColumns={[
              'serialNumber',
              'year',
              'late',
              'leave',
              'absence',
              'leaveEarly',
              'prisonTermDay',
              'openState',
              'edit'
            ]}
            />
            </div>
        );
    }
}

 

export default stripesConnect(injectIntl(List));
